package com.thomas.framework.utils;

import com.thomas.framework.core.AppException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by taohj on 2014/5/5.
 */
public class CommonUtil {

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static Date dateParse(String date, String patten) {

        if (!StringUtils.hasLength(date)) {
            return null;
        }

        Date d = null;

        try {
            SimpleDateFormat format = new SimpleDateFormat(patten);
            d = format.parse(date);
        } catch (ParseException e) {
            throw new AppException(date + ",格式化成--" + patten + "--失败");
        }

        return d;
    }

    public static Date dateParse(String date) {
        return dateParse(date, "yyyy-MM-dd");
    }

    public static Date dateParseSS(String date) {
        return dateParse(date, "yyyy-MM-dd HH:mm:ss");
    }



    public static String dateFormat(Date date, String patten) {
        String result = "";
        if (date == null) {
            return result;
        }
        SimpleDateFormat format = new SimpleDateFormat(patten);
        result = format.format(date);
        return result;
    }

    public static String dateParse(Date date) {
        return dateFormat(date, "yyyy-MM-dd");
    }

    public static String dateFormateSS(Date date) {
        return dateFormat(date, "yyyy-MM-dd HH:mm:ss");
    }


    public static void initPageResult(PageResult pageResult, HttpServletRequest request) {

        String page = request.getParameter("page");
        String size = request.getParameter("rows");

        page = StringUtils.hasLength(page) ? page : "1";
        size = StringUtils.hasLength(size) ? size : "20";

        pageResult.setPage(Integer.valueOf(page));
        pageResult.setSize(Integer.valueOf(size));
        pageResult.setSort("t."+request.getParameter("sort"));
        pageResult.setOrder(request.getParameter("order"));

    }



}
